from flask import g
from flask_restful import fields, marshal
from flask_restful import reqparse, abort, Resource
from apps.apis.cinema.utils import login_required
from apps.models.cinema import Hall, CinemaAddress

parse = reqparse.RequestParser()
parse.add_argument("h_num", required=True, help="请提供放映厅编号")
parse.add_argument("h_seats", required=True, help="请提供放映厅布局")
parse.add_argument("h_address_id", type=int, required=True, help="请提供电影院地址")

hall_fields = {
    "address_id": fields.Integer,
    "num": fields.Integer,
    "seats": fields.String
}


class CinemaHallsResource(Resource):
    @login_required
    def post(self):
        args = parse.parse_args()
        num = args.get("num")
        seats = args.get("seats")
        address_id = args.get("address_id")
        cinema_addresses = CinemaAddress.query.filter_by(cinema_user_id=g.user.id).all()
        cinema_ids = []
        for cinema_address in cinema_addresses:
            cinema_ids.append(cinema_address.id)
        if not address_id in cinema_ids:
            abort(400, msg="error action")

        hall = Hall()

        hall.address_id = address_id
        hall.num = num
        hall.seats = seats

        if not hall.save():
            abort(400, msg="放映厅创建失败")

        data = {
            "msg": "create success",
            "status": 201,
            "data": marshal(hall, hall_fields)
        }

        return data
